package com.weifly.egp.gui;

import com.weifly.egp.service.ServiceManager;
import com.weifly.egp.service.monitor.StockInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * Created by weijianxin on 2018/8/26.
 */
public class GuiMain {

    private Logger logger = LoggerFactory.getLogger(GuiMain.class);

    private ServiceManager serviceManager;

    private JFrame rootFrame;

    private JFileChooser fileChooser;

    private StockTableModel stockTableModel;

    private JTable stockTable;

    public void setServiceManager(ServiceManager serviceManager) {
        this.serviceManager = serviceManager;
    }

    public void render(){
        this.rootFrame = new JFrame("挂单插件");
        this.rootFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //this.rootFrame.setFont(new Font("Dialog", Font.PLAIN, 16));

        createNorthPanel(this.rootFrame);

        createCenterPanel(this.rootFrame);

        this.initFileChooser();

        // 监听股票变更事件
        this.listenStockListEvent();

        // 全屏显示
        this.rootFrame.setUndecorated(false);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle bounds = new Rectangle(screenSize);
        this.rootFrame.setBounds(bounds);
        this.rootFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.rootFrame.setVisible(true);
        this.rootFrame.toFront();
    }

    private void createNorthPanel(JFrame frame){
        JPanel northPanel = new JPanel();
        northPanel.setSize(300, 50);
        northPanel.setBackground(Color.GREEN);

        FlowLayout layout = new FlowLayout();
        layout.setAlignment(FlowLayout.LEFT); //左对齐
        northPanel.setLayout(layout);

        frame.add(northPanel, BorderLayout.NORTH);

        JButton loadConfigButton = new JButton("加载配置文件");
        loadConfigButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                handleLoadConfigButtonClick();
            }
        });
        northPanel.add(loadConfigButton);
    }

    private void handleLoadConfigButtonClick(){
        int returnVal = this.fileChooser.showOpenDialog(this.rootFrame);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File configFile = this.fileChooser.getSelectedFile();
            try{
                this.serviceManager.getGridConfigService().setConfigFile(configFile);
                List<StockInfo> stockList = this.serviceManager.getGridConfigService().parseConfig();
                this.serviceManager.getStockMonitorService().setStockList(stockList);
                //this.stockUpdateService.notifyUpdateThread();
            }catch(Exception e){
                logger.error("解析配置文件出错", e);
            }
        }
    }

    private void listenStockListEvent(){
        this.serviceManager.getStockMonitorService().addStockListListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        int selectedRowIndex = stockTable.getSelectedRow();
                        int stockIndex = -1;
                        StockInfo stockInfo = null;
                        if(selectedRowIndex>=0){
                            stockIndex = stockTable.convertRowIndexToModel(selectedRowIndex);
                            if(stockIndex>=0){
                                stockInfo = serviceManager.getStockMonitorService().getStockByIndex(stockIndex);
                            }
                        }

                        stockTableModel.fireTableDataChanged();

                        if(stockInfo!=null){
                            int viewIndex = stockTable.convertRowIndexToView(stockIndex);
                            if(viewIndex>=0){
                                stockTable.setRowSelectionInterval(viewIndex, viewIndex);
                            }
                        }
                    }
                });
            }
        });
    }

    private void initFileChooser(){
        this.fileChooser = new JFileChooser();
        FileFilter filter = new FileFilter(){
            public boolean accept(File f) {
                if(f.isDirectory()){
                    return true;
                }
                String fn = f.getName();
                if(fn.endsWith(".xml")){
                    return true;
                }
                return false;
            }
            public String getDescription() {
                return "xml";
            }
        };
        this.fileChooser.setFileFilter(filter);
    }

    private void createCenterPanel(JFrame frame){
        this.stockTableModel = new StockTableModel(this.serviceManager.getStockMonitorService());
        DefaultTableColumnModel tableColumnModel = new DefaultTableColumnModel();
        // 表格渲染器
        StockTableCellRenderer cellRenderer = new StockTableCellRenderer();
        // 名称
        TableColumn stockNameColumn = new TableColumn(StockTableModel.COLUMN_stockName);
        stockNameColumn.setHeaderValue("名称");
        stockNameColumn.setPreferredWidth(40);
        stockNameColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(stockNameColumn);
        // 代码
        TableColumn stockCodeColumn = new TableColumn(StockTableModel.COLUMN_stockCode);
        stockCodeColumn.setHeaderValue("代码");
        stockCodeColumn.setPreferredWidth(40);
        stockCodeColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(stockCodeColumn);
        // 最新价
        TableColumn newestPriceColumn = new TableColumn(StockTableModel.COLUMN_newestPrice);
        newestPriceColumn.setHeaderValue("最新价");
        newestPriceColumn.setPreferredWidth(50);
        newestPriceColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(newestPriceColumn);
        // 买入委托
        TableColumn buyStatusColumn = new TableColumn(StockTableModel.COLUMN_buyStatus);
        buyStatusColumn.setHeaderValue("买入委托");
        buyStatusColumn.setPreferredWidth(160);
        buyStatusColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(buyStatusColumn);
        // 卖出委托
        TableColumn sellStatusColumn = new TableColumn(StockTableModel.COLUMN_sellStatus);
        sellStatusColumn.setHeaderValue("卖出委托");
        sellStatusColumn.setPreferredWidth(160);
        sellStatusColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(sellStatusColumn);
        // 基准价格
        TableColumn basePriceColumn = new TableColumn(StockTableModel.COLUMN_basePrice);
        basePriceColumn.setHeaderValue("基准价格");
        basePriceColumn.setPreferredWidth(40);
        basePriceColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(basePriceColumn);
        // 网格价差
        TableColumn gridPriceColumn = new TableColumn(StockTableModel.COLUMN_gridPrice);
        gridPriceColumn.setHeaderValue("网格价差");
        gridPriceColumn.setPreferredWidth(40);
        gridPriceColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(gridPriceColumn);
        // 每次交易量
        TableColumn tradeUnitColumn = new TableColumn(StockTableModel.COLUMN_tradeUnit);
        tradeUnitColumn.setHeaderValue("每次交易量");
        tradeUnitColumn.setPreferredWidth(40);
        tradeUnitColumn.setCellRenderer(cellRenderer);
        tableColumnModel.addColumn(tradeUnitColumn);

        this.stockTable = new JTable(stockTableModel, tableColumnModel);
        this.stockTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // 排序
        this.stockTable.setRowSorter(new TableRowSorter(this.stockTableModel));
        // 表格渲染
        cellRenderer.setStockTable(this.stockTable);
        cellRenderer.setStockMonitorService(this.serviceManager.getStockMonitorService());

        JScrollPane scrollPane = new JScrollPane(this.stockTable);
        frame.add(scrollPane, BorderLayout.CENTER);
    }
}
